package com.ybwh.datasource.refreshable.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.ybwh.datasource.refreshable.core.datasource.AbstractDelegatedRefreshDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Objects;

/**
 * <p>
 * 包装DruidDataSource的可刷新数据源
 *
 * </p>
 *
 * @author fanbeibei
 * @version V1.0
 * @since 2019/4/5 23:19
 */
@Slf4j
@Data
public class DruidRefreshDataSource extends AbstractDelegatedRefreshDataSource {

    private DruidRefreshDataSourceProperties properties;


    public DruidRefreshDataSource(DruidRefreshDataSourceProperties properties) {
        Objects.requireNonNull(properties, "arg is null!");

        this.properties = properties;
    }


    @Override
    protected DataSource createDataSource() throws SQLException {
        return createDruidDataSource();
    }

    @Override
    protected void destroyDataSource(DataSource dataSource) throws Exception {
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        druidDataSource.close();
    }

    private DruidDataSource createDruidDataSource() throws SQLException {


        DruidDataSource dataSource = new DruidDataSource();
        BeanUtils.copyProperties(properties, dataSource);
        dataSource.init();

        return dataSource;
    }

    @Override
    public String toString() {
        return "datasource:" + properties.getUrl();
    }

    @Override
    public void beforeRefresh() {

    }

    @Override
    public void afterRefresh() {

    }
}
